import React, { Component } from "react";
import { Modal, Input, Form } from "antd";
export default class TableListModal extends Component {
  state = {
    isModalVisible: false,
    age1: "",
    name1: "",
    ass1: "",
    key1: "",
  };

  handleOk = () => {
    let NewObj = this.form.getFieldValue();
    if (this.state.key1) {
      this.props.getValue({ ...NewObj, key: this.state.key1 });
    } else {
      this.props.getValue({ ...NewObj }); //获取表单数据，传递给父组件
    }
    this.setState({
      isModalVisible: !this.state.isModalVisible,
    });
    this.form.resetFields();
  };

  showModal = (e) => {
    console.log(e);
    if (e) {
      this.setState({
        age1: e.age,
        name1: e.name,
        ass1: e.address,
        key1: e.key,
        isModalVisible: !this.state.isModalVisible,
      });
    } else {
      this.setState({
        isModalVisible: !this.state.isModalVisible, //add打开表单
        age1: "",
        name1: "",
        ass1: "",
        key1: "",
      });
      this.form.resetFields();
    }
  };

  componentDidUpdate() {
    const { name1, ass1, age1 } = this.state;
    if (this.state.key1) {
      this.form.setFieldsValue({
        Name: name1,
        Address: ass1,
        Age: age1,
      });
    }
  }

  handleCancel = () => {
    this.form.resetFields();
    this.setState({
      //关闭清空表单，关闭对话框
      isModalVisible: !this.state.isModalVisible,
    });
  };

  render() {
    const { isModalVisible } = this.state;

    return (
      <div>
        <Modal
          title="添加"
          visible={isModalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form
            ref={(e) => (this.form = e)}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            autoComplete="off"
          >
            <Form.Item
              label="Name"
              name="Name"
              rules={[
                {
                  required: true,
                  message: "Please input your name",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item label="Address" name="Address">
              <Input />
            </Form.Item>

            <Form.Item label="Age" name="Age">
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
